<?php

class DefaultController extends FController {

    public $user_school_list;
    public $user_subject_list;
    public $user_role_list;
    public $exam_id;
	public function accessRules() {
        $config = array(
            'index' => 1
        );
        return ZRole::auth("notice", $config);
    }
	public function __common() {
        parent::init();

        if (empty($this->cLoginUser)) {
            $this->redirect($this->createUrl('/site/login'));
        }else{
            $userLoginUser = $this->cLoginUser;
            $this->user_role_list = isset($userLoginUser['cuser']['role_id']) ? $userLoginUser['cuser']['role_id'] : '';
            $this->user_school_list = isset($userLoginUser['cuser']['school']['school_id']) ? $userLoginUser['cuser']['school']['school_id'] : '';
            $this->user_subject_list = isset($userLoginUser['cuser']['school']['subject_id']) ? $userLoginUser['cuser']['school']['subject_id'] : '';
            $zRow = new ZRole();
            //得到学校对应的考试
            $exam_list = $zRow->_getSchoolExam($this->user_school_list);
            if(!empty($exam_list)){
                $this->exam_id = implode(',', $exam_list);
            }
        }

        $this->commonScript();
        Yii::app()->clientScript->registerCssFile(THEME_CSS_URL . '/module_Sip.css');
    }

    public function actionIndex() {

		
		Yii::app()->clientScript->registerScriptFile(STATICS_URL . "/js/My97DatePicker/WdatePicker.js");
		$this->__common();
		$this->title ='通知信息维护';
		$conn = Yii::app()->db;

		$s['exam_id'] = Yii::app()->request->getParam('exam_id');
                
		$where = ' AND "expired" >= \''.strtotime(date("Y-m-d")).'\'';
		$order = ' ORDER BY "update_time" DESC';

		#  拼接条件  #
		if(!empty($s['exam_id'])){
			$where.= ' AND A."exam_id" ='.$s['exam_id'];
                } else {

                    //权限判断
                    if ($this->user_role_list != 1 && !empty($this->exam_id)) {
                        $where .= ' AND "exam_id" IN (' . $this->exam_id . ')';
                    }
                }

		$select = 'SELECT * FROM "{{exam_notice}}" A ';
		$sql = " WHERE 1=1 ".$where;

		$selectSql = $select.$sql.$order;
		$countSql = 'SELECT COUNT(*) FROM "{{exam_notice}}" A '.$sql;
		$data = ZCommon::getDaoPageList($selectSql, $countSql, 8);
		if(!empty($data['listDatas'])){
			$temp = array();
			foreach($data['listDatas'] as $key=>$value){
				$userInfo = User::model()->findByPk($value['user_id']);
				$temp['username'] =  (!empty($userInfo->username)) ? $userInfo->username : '';

				$data['listDatas'][$key] = array_merge($data['listDatas'][$key],$temp);
			}
		}
		#  取所有考试项目  #
		$zExam = new zExam();
        $info['examData'] = $zExam->_getExamObject($this->exam_id, $this->user_role_list);
		
		$pageUrl = $this->createUrl('/notice/default/index',$s);
		$this->render('index',array(
			'data'	=>$data['listDatas'],
			'pages' => $data['pages'],
			'pageUrl' => $pageUrl,
			'info'	  => $info,
			'search'	=> $s
		));

	}

	public function actionAdd(){
        $this->__common();
		Yii::app()->clientScript->registerScriptFile(STATICS_URL . "/js/My97DatePicker/WdatePicker.js");
		Yii::app()->clientScript->registerScriptFile(STATICS_URL . "/js/ueditor/editor_config.js", CClientScript::POS_BEGIN);
        Yii::app()->clientScript->registerScriptFile(STATICS_URL . "/js/ueditor/editor_api.js", CClientScript::POS_BEGIN);
        
		Yii::app()->clientScript->registerCssFile(STATICS_URL . "/js/uploadify/uploadify.css");
      	Yii::app()->clientScript->registerScriptFile(STATICS_URL . "/js/uploadify/jquery.uploadify.min.js");
		$userInfo = $this->cLoginUser;


		if(!empty($_POST['submit'])){
		
			$model = new ExamNotice();
			$data = ZTask::dis_input($_POST['info']);
			$data['notice_comment'] = $_POST['info']['notice_comment'];
			if (!empty($_POST['path'])){
				$data['file'] = '';
				$data['file_name'] = '';
				$count = count($_POST['path']) - 1;
				$path = self::_getUpload_path();
				foreach ($_POST['path'] as $k=>$v){
					if ($k == $count){
						$data['file'].= $path.'/'.$v;
					}else{
						$data['file'].= $path.'/'.$v."||";
					}
				}
				
				foreach ($_POST['pathname'] as $k=>$v){
					if ($k == $count){
						$data['file_name'].= $v;
					}else{
						$data['file_name'].= $v."||";
					}
				}
			}
			
			$data['expired'] = (!empty($data['expired'])) ? strtotime($data['expired']) : time();
			$data['notice_status'] = (!empty($data['notice_status'])) ? $data['notice_status'] : 0 ;
			$data['time_created'] = time();
			$data['user_id'] = $userInfo['cuser']['id'];  // 用户id
			$data['create_user'] = $this->cLoginUser['cuser']['id'];
           	$data['create_time'] = time();
           	$data['update_user'] = $this->cLoginUser['cuser']['id'];
           	$data['update_time'] = time();
			

			$model->attributes = $data;
			if($model->save()){
				$this->frameAjaxMessage ('index');
				exit;
			}else{
				$this->frameAjaxMessage ( null,'添加失败' );
				exit;
			}
			exit;

		}
		#  取所有考试项目  #
        $zExam = new zExam();
        $info['examData'] = $zExam->_getExamObject($this->exam_id, $this->user_role_list);
                $this->title = "新增考试项目通知";
		$this->render('add',array(
			'info'	=>$info,
			'userInfo' => $userInfo
		));
	}


	public function actionUpdate(){
        $this->__common();
		Yii::app()->clientScript->registerScriptFile(STATICS_URL . "/js/My97DatePicker/WdatePicker.js");
		Yii::app()->clientScript->registerScriptFile(STATICS_URL . "/js/ueditor/editor_config.js", CClientScript::POS_BEGIN);
        Yii::app()->clientScript->registerScriptFile(STATICS_URL . "/js/ueditor/editor_api.js", CClientScript::POS_BEGIN);
        
     	Yii::app()->clientScript->registerCssFile(STATICS_URL . "/js/uploadify/uploadify.css");
      	Yii::app()->clientScript->registerScriptFile(STATICS_URL . "/js/uploadify/jquery.uploadify.min.js");
		$userInfo = $this->cLoginUser;
		$conn = Yii::app()->db;

		$notice_id = Yii::app()->request->getParam('notice_id');
		$notice_id = (!empty($_POST['info']['notice_id'])) ? $_POST['info']['notice_id'] : $notice_id;

		$noticeModel = ExamNotice::model()->findByPk($notice_id);
		if(empty($noticeModel)){
			$this->frameAjaxMessage('index');
			exit;
		}

		if(!empty($_POST['submit'])){
			$data = ZTask::dis_input($_POST['info']);
			$data['notice_comment'] = $_POST['info']['notice_comment'];
			$model = new ExamNotice();
				$path = self::_getUpload_path();
			if (!empty($_POST['path'])){
				$data['file'] = '';
				$data['file_name'] = '';
				$count = count($_POST['path']) - 1;
				foreach ($_POST['path'] as $k=>$v){
					if ($k == $count){
						$data['file'].= $path.'/'.$v;
					}else{
						$data['file'].= $path.'/'.$v."||";
					}
				}
				
				foreach ($_POST['pathname'] as $k=>$v){
					if ($k == $count){
						$data['file_name'].= $v;
					}else{
						$data['file_name'].= $v."||";
					}
				}
			}
			
			$data['expired'] = (!empty($data['expired'])) ? strtotime($data['expired']) : time();
			$data['notice_status'] = (!empty($data['notice_status'])) ? $data['notice_status'] : 0 ;
			$data['time_created'] = time();
			$data['user_id'] = $userInfo['cuser']['id'];  // 用户id
           	$data['update_user'] = $this->cLoginUser['cuser']['id'];
           	$data['update_time'] = time();
			
			
			$noticeModel->attributes = $data;
			if($noticeModel->save()){
			
				$this->frameAjaxMessage('index');
			}else{
				
				$this->frameAjaxMessage(null,'更新失败!');
			}
			exit;

		}
		
			#  取所有考试项目  #
        $zExam = new zExam();
        $info['examData'] = $zExam->_getExamObject($this->exam_id, $this->user_role_list);
		$this->title = "编辑考试项目通知";
		$this->render ( 'update', array ('data' => $noticeModel->attributes, 'info' => $info ,'userInfo' => $userInfo) );
	}


	/**
	*	@ 删除
	*	@ yindebin
	*	@ 2013-12-14 AM
	*/
    public function actionDelete() {
		$this->__common();
        $notice_id = (int)Yii::app()->request->getparam('notice_id');

		if(!empty($notice_id)){
			$model = ExamNotice::model()->findByPk($notice_id);
			if(empty($model)){
				$this->redirect ( $this->createUrl ( 'index' ) );
				exit;
			}
            if (!empty($model->file)) {
			    //$webroot = Yii::getPathOfAlias('webroot');
			   
			   @ unlink(UPLOAD_PATH.$model->file);
			}				
				
			if ($model->model()->deleteAll('"notice_id"=:notice_id',array(':notice_id'=>$notice_id))) {

				$this->redirect ( $this->createUrl ( 'index' ) );
				exit;
			} else {
				$this->redirect ( $this->createUrl ( 'index' ) );
				exit;
			}
		}else{
			$this->redirect ( $this->createUrl ( 'index' ) );
		}
    }
	
	/**
     * @ 文件下载
     * 
     */
    public function actionDownload() {
        $notice_id = Yii::app()->request->getparam('notice_id');
        if (!empty($notice_id)) {
            $model = ExamNotice::model()->findByPk($notice_id);
            if (!empty($model)) {
                $data = $model->attributes;

                if (!empty($data['file'])) {
                
                    $file = explode('||', $data['file']);
                    $file_name = explode('||', $data['file_name']);
                    $next = (int) Yii::app()->request->getparam('num');
                    $name = substr(strrchr($file[$next - 1], '/'), 1);
                    if (file_exists(UPLOAD_PATH . '/' . $file[$next - 1])) {
                        $files = fopen(UPLOAD_PATH . '/' . $file[$next - 1], "r"); // 打开文件
                        // 输入文件标签
                        	ob_end_clean();
                        Header("Content-type: application/octet-stream");
                        Header("Accept-Ranges: bytes");
                        Header("Accept-Length: " . filesize(UPLOAD_PATH . $file[$next - 1]));
                        Header("Content-Disposition: attachment; filename=" . $file_name[$next - 1]);
                        // 输出文件内容

                        echo fread($files, filesize(UPLOAD_PATH . $file[$next - 1]));
                        fclose($files);
                        exit;
                    } else {
                        $message = '文件不存在';
                        echo 2;
                        exit;
                    }
                }
            }
        } else {
            $message = '参数错误';
            echo 1;
            exit;
        }
    }
    
    	/**
    	 * @ 批量上传接收文件
    	 * @ yindebin
    	 * @ 2014-01-11
    	 */
   	 	public function actionUpload_ajax(){
    			if(!empty($_FILES['Filedata'])){
	   	 			$size = 2 * 1024 * 1024;
	    			$data = array();
	    			$uid = Yii::app()->request->getParam('uid');
					$path = UPLOAD_PATH.'/exam_notice/'.$uid;
					
					#$path_url = '/exam_notice/'.$uid;  // 文件下载的地址
				
					if(!file_exists($path)){
						mkdir($path,0777,true);
					}
									
					$extend = substr(strrchr($_FILES["Filedata"]["name"],'.'), 1);  // 取扩展名
					$name = time().'.'.$extend;
					
					$data['path'] = $name;
					$data['name'] = $_FILES["Filedata"]["name"];
					
					$data['successs'] = $status = move_uploaded_file($_FILES["Filedata"]["tmp_name"],$path.'/'.$name);
					if (!empty($status))
						echo json_encode($data);
    			}
    	}
    	public function actionMove_path(){
    		$name = Yii::app()->request->getParam('name');
    		$path = self::_getUpload_path();
    		@ unlink(UPLOAD_PATH.$path.'/'.$name);
    	}
    	
    protected function _getUpload_path(){
    	return $path_url = '/exam_notice/'.$this->cLoginUser['cuser']['id'];
    
    } 
	/**
	* @ 批量删除学段
	* @ yindebin
	* @ 2014-01-06 pm
	*
	*/
	public function actionDelete_all(){
		$notice_id = Yii::app ()->request->getparam ( 'notice_id' );
		if (! empty ( $notice_id )) {
			$sql = 'SELECT "file" FROM "{{exam_notice}}" WHERE "notice_id" IN('.$notice_id.')';
			$data = Yii::app()->db->createCommand($sql)->queryAll();
			$delete = 'DELETE FROM "{{exam_notice}}" WHERE "notice_id" IN ('.$notice_id.')';
			$query = Yii::app()->db->createCommand($delete)->execute();
			if(!empty($query)){
				if(!empty($data)){
					foreach($data as $k=>$v){
						if(!empty($v['file'])){
							$path = explode('||', $v['file']);
							foreach ($path as $pk=>$pv){
								@ unlink(UPLOAD_PATH.$pv);
							}
						}
					}
				}
			}
			exit;
			echo 1;
		}else{
			echo 2;
		}
	}

}